package LeetCode热题HOT100;

import java.util.HashMap;
import java.util.Map;

public class p1两数之和 {
    public int[] twoSum1(int[] nums, int target) {
        //暴力枚举
        int[] res=new int[2];

        for (int i = 0; i <nums.length; i++) {
            for(int j=i+1;j<nums.length;j++) {
                if (nums[i]+nums[j]==target) {
                    res[0]=nums[i];
                    res[1]=nums[j];
                    break;
                }
            }
        }

        return res;
    }

    public int[] twoSum(int[] nums, int target) {
        //哈希表
        Map<Integer,Integer> map=new HashMap<>();
        int[] res=new int[2];

        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target-nums[i])) {
                res[0]=map.get(target-nums[i]);//通过key，得到value 这里就是下标
                res[1]=i;
                break;
            }
            map.put(nums[i],i); //向 map 中放入 数组元素-元素下标
        }
        return res;
    }
}
